package com.dustedpixels.jasmin.chips.z80.util;

import com.dustedpixels.jasmin.chips.z80.Z80;

/**
 * Prints the state of the Z80 onto standard output.
 */
public class Z80StatePrinter {
    /**
     * Writes the state of Z80.
     * 
     * @param z80
     */
    void printState(Z80 z80) {
        System.out.println("F: " + flags(z80.getF())
                + " F': " + flags(z80.getF2()));
        System.out.println("AF: " + wordAsHex(z80.getAF())
                + " AF': " + wordAsHex(z80.getAF2()));
        System.out.println("BC: " + wordAsHex(z80.getBC())
                + " BC': " + wordAsHex(z80.getBC2()));
        System.out.println("DE: " + wordAsHex(z80.getDE())
                + " DE': " + wordAsHex(z80.getDE2()));
        System.out.println("HL: " + wordAsHex(z80.getHL())
                + " HL': " + wordAsHex(z80.getHL2()));
        System.out.println("IX: " + wordAsHex(z80.getIX()));
        System.out.println("IY: " + wordAsHex(z80.getIY()));
        System.out.println("PC: " + wordAsHex(z80.getPC()));
        System.out.println("SP: " + wordAsHex(z80.getSP()));
        System.out.println("IR: " + byteAsHex(z80.getI())
                + byteAsHex(z80.getR()));
        System.out.println("IFF1: " + (z80.getIFF1() ? "1" : "0")
                + " IFF2: " + (z80.getIFF2() ? "1" : "0"));
        System.out.println("IM: " + z80.getIM());
    }
    
    private String byteAsHex(byte i) {
        return Integer.toHexString(0x100 | (i & 0xFF)).substring(1).toUpperCase();
    }

    private String wordAsHex(short i) {
        return Integer.toHexString(0x10000 | (i & 0xFFFF)).substring(1).toUpperCase();
    }
    
    private String flags(int f) {
        char[] chars = {'S', 'Z', 'Y', 'H', 'X', 'P', 'N', 'C'};
        
        for (int i = 0; i < 8; i++) {
            if ((f & (0x01 << (7 - i))) == 0) {
                chars[i] = '-';
            }
        }
        
        return new String(chars);
    }
}
